package com.jml.注册校验器;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@Controller
@RequestMapping("/model")
public class ModelAttributeController {

    //设置了value就将其设置为参数名，返回值作为参数设置到Model
    //执行处理器前给Model设置("className","com.jml.注册校验器.ModelAttributeController")
    @ModelAttribute("className")
    public String setModel(){
        return this.getClass().getName();
    }

    //方法含有Model，Map，ModelMap类型的参数，则可以将直接需要的参数设置上去
    //执行处理器前给Model设置("teacher","Mr-jml")
    @ModelAttribute
    public void setModel1(Model model){
        model.addAttribute("teacher","Mr-jml");
    }

    //没有设置value也没有设置Model类型参数则根据返回值类型解析参数名
    //执行处理器前给Model设置("string","excelib")
    @ModelAttribute
    public String setModel2(){
        return "excelib";
    }

    //执行处理器
    @RequestMapping(value={"/index"},method = RequestMethod.GET)
    public String userIndex(Model model, HttpServletRequest request){
        Map<String, Object> m = model.asMap();
        System.out.println(m.get("className"));
        System.out.println(m.get("teacher"));
        System.out.println(m.get("string"));
        return "user.jsp";
    }

    @RequestMapping(value={"/RequestBodyAdvice"},method = RequestMethod.GET)
    @ResponseBody public String RequestBodyAdvice(Model model, HttpServletRequest request){
        Map<String, Object> m = model.asMap();
        System.out.println(m.get("className"));
        System.out.println(m.get("teacher"));
        System.out.println(m.get("string"));
        return "user.jsp";
    }
}
